/**
 * 样式构造工具函数
 */
import { Circle, Fill, Icon, RegularShape, Stroke, Style, Text } from 'ol/style'

const PROPS_MAP: any = {
  fill: Fill,
  text: Text,
  stroke: Stroke,
  circle: Circle,
  icon: Icon,
  regularShape: RegularShape,
  backgroundFill: Fill,
  backgroundStroke: Stroke
}

const IMAGE_PROPS: any[] = [Circle, Icon, RegularShape]

function isObject(value: any) {
  return typeof value === 'object'
}

function parseFill(fill: any) {
  const opts = isObject(fill) ? fill : { color: fill }
  return new Fill(opts)
}

function parseValue(Model: any, key: any, value: any) {
  if (value === undefined || value === null) return
  if (!Model) return value
  if (['fill', 'backgroundFill'].includes(key)) return parseFill(value)
  if (key === 'text') {
    console.log(value)

    return isObject(value) ? parse(value, Model) : value
  }
  return parse(value, Model)
}

// { text, stroke, circle}
/**
 * 构建样式
 * @param {Object} settings 配置 { text, stroke, circle, fill, icon, image}
 * @param {Object} [StyleModel]
 * @return {Style}
 */
function parse(settings: any, StyleModel?: any) {
  const opts: any = {}
  Object.entries(settings).forEach(([key, value]) => {
    const Model = PROPS_MAP[key]
    if (key === 'font') {
      value = `${value} sans-serif`
    }
    opts[IMAGE_PROPS.includes(Model) ? 'image' : key] = parseValue(Model, key, value)
  })
  return new (StyleModel || Style)(opts)
}

export default parse
